﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ROrganizer.Client;

namespace ROrganizer.UI.Controllers
{
    internal class FileDetailsFormController
    {
        private readonly string path;
        private readonly HashEntry entry;
        private readonly ImdbFacility ifacility;
        private string link;
        private string id;
        private bool computed;

        public FileDetailsFormController(string path)
        {
            var hrepository = new HashRepository();
            var hfacility = new HashFacility();

            this.ifacility = new ImdbFacility();
            this.entry = hrepository.Get(path);
            this.path = path;

            if (entry == null)
            {
                entry = hfacility.ComputeHash(path);
                computed = true;
            }

            if (!String.IsNullOrWhiteSpace(this.entry.Info.Link))
                this.link = this.ifacility.FormatLink(this.entry.Info.Link);
        }

        public string File
        {
            get { return this.path; }
        }

        public string Hash
        {
            get { return this.entry.Info.Hash; }
        }

        public string Link
        {
            get { return this.link; }
            set 
            {
                this.link = value;
                this.id = this.ifacility.GetId(value);
            }
        }

        public void OpenFile()
        {
            if (System.IO.File.Exists(this.File))
                Process.Start(this.File);
        }

        public bool CanOpenImdbLink()
        {
            return this.ifacility.IsValidLink(this.Link);
        }

        public void OpenImdbLink()
        {
            Process.Start(this.Link);
        }

        public bool CanCommit()
        {
            return (this.ifacility.IsValidLink(this.Link) || String.IsNullOrEmpty(this.Link))
                && (computed || this.id != this.entry.Info.Link);
        }

        public void Commit()
        {
            var hrepository = new HashRepository();
            var irepository = new ImdbRepository();
            var igateway = new ImdbGateway();

            this.entry.Info.Link = this.id;
            this.entry.IsChanged = !String.IsNullOrEmpty(this.id);
            hrepository.SaveOrUpdate(this.entry);

            var imdb = igateway.Query(this.entry);
            if (imdb != null)
                irepository.SaveOrUpdate(imdb);
        }
    }
}
